package net.joyphper.ctrl.security;

import java.util.Date;
import java.util.Set;

import net.joyphper.bean.User;
import net.joyphper.commons.ResponseJson;
import net.joyphper.commons.security.Auth;
import net.joyphper.commons.security.SecurityUtil;
import net.joyphper.commons.utils.Tools;
import net.joyphper.enums.UserStatus;
import net.joyphper.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("net.joyphper.ctrl.security.AuthCtrl")
public class AuthCtrl {
//	private final Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private SecurityUtil securityUtil;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/auth/login.htm",method=RequestMethod.GET)
	public String login(){
		return "/auth/login";
	}
	
	@RequestMapping(value="/auth/login.htm",method=RequestMethod.POST)
	@ResponseBody
	public ResponseJson login(ModelMap map,String loginMail,String loginPwd,String captcha) throws Exception{
		if(!this.securityUtil.compareCaptcha(captcha)){
			return ResponseJson.body(false, "验证码错误，请输入正确的验证码");
		}
		if(!Tools.isMail(loginMail)){
			return ResponseJson.body(false, "登录失败，请确认是否输入正确的邮箱地址和密码");
		}
		
		User user = this.userService.getUserByLoginMail(loginMail);
		
		if(user == null){
			return ResponseJson.body(false, "登录失败，请确认是否输入正确的邮箱地址和密码");
		}
		
		if(!UserStatus.OK.equals(user.getStatus())){
			return ResponseJson.body(false, "登录失败，您的账号状态不可用，请与管理员联系");
		}
		
		String pwd = this.securityUtil.genPwd(loginMail, loginPwd);
		
		if(user.getLoginPasswd().equals(pwd)){
			this.userService.updateLoginTime(new Date(), user.getId());
			Set<String> resources = this.userService.getResourcesIdByUserId(user.getId());
			Set<Long> roles = this.userService.getRolesIdByUserId(user.getId());
			
			Auth auth = new Auth(user.getId(),user.getLoginMail(),user.getStatus(),user.getLastLoginTime(),resources,roles);
			this.securityUtil.setAuth(auth);
			return ResponseJson.body(true,"登录成功。。。",true);
		}else{
			return ResponseJson.body(false, "登录失败，请确认是否输入正确的邮箱地址和密码");
		}
	}
	
	@RequestMapping(value="/auth/logout.htm",method=RequestMethod.GET)
	public String logout(){
		this.securityUtil.destroyAuth();
		return "redirect:/auth/login.htm";
	}
}
